<template>
    <el-dialog v-model="dialogVisible" @close="handleClose" :title="dialogTitle" width="95%" >

        <div class="header-controls">
          <el-button  type="primary" @click="initDicom"> 初始化</el-button>

          <el-input v-model="studyInstanceUid" placeholder="请输入检查实例UID" style="width: 300px; margin-right: 10px;"
            disabled />
          <el-select v-model="seriesInstanceUid" placeholder="请选择序列实例" style="width: 300px; margin-right: 10px;">
            <el-option v-for="series in seriesInstanceUidOptions" :key="series.seriseId"
              :label="series.seriseId" :value="series.seriseId" />
          </el-select>

          <el-button type="primary" @click="loadDicomViewer" >
            加载影像
          </el-button>
        </div>

        <!-- DICOM图像显示区域 -->
        <div id="dicom-viewport" class="viewport"></div>
      
    </el-dialog>
</template>

<script setup>

import { getSeriseAllList } from "@/api/pacs/serise/serise"
import { DicomDataService } from '@/api/pacs/dicom/dicomService.js'
import {getSeriesImages} from '@/api/pacs/dicom/dicom.js'

import {
  createQiniuImageIds
} from "@/utils/dicom/dicom";


import {
  Enums as csEnums,
  RenderingEngine,
  imageLoader,
 
  init as coreInit
} from '@cornerstonejs/core'

import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
import { nextTick } from "vue";



// 创建DicomDataService实例
const dicomService = new DicomDataService();



// 接收父组件传递的属性
const props = defineProps({
  // 是否显示对话框
  modelValue: {
    type: Boolean,
    default: false
  },

  // 对话框标题
  title: {
    type: String,
    default: 'DICOM 医学影像查看器'
  },

  // 初始检查实例ID
  initialStudyId: {
    type: Number,
    default: null,
  },
  // 初始检查实例UID
  initialStudyUid: {
    type: String,
    default: ''
  }

})

// 定义 emits 
const emit = defineEmits(['update:modelValue', 'close'])

//dialog 是否显示(使用V-model)
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => {
    emit('update:modelValue', value)
  }
})

//dialog 的标题
const dialogTitle = computed(() => props.title)


const studyId = ref(props.initialStudyId) //studyID
const studyInstanceUid = ref(props.initialStudyUid)  //studyUId
const seriesInstanceUid = ref('') //Series UID
const seriesInstanceUidOptions = ref([])

// 视图DOM引用
const viewportRef = ref(null)

/***
 *  ViewPort 和 renderingEngine
 */

let viewportId = 'CT_STACK'
let renderingEngineId = 'myRenderingEngine'
let viewPort = null
let renderingEngine = null



// 监听props变化，当对话框打开/关闭时执行相应操作
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 对话框打开时，重置数据
    studyId.value = props.initialStudyId
    studyInstanceUid.value = props.initialStudyUid
    
    // 延迟一下确保DOM渲染完成
    setTimeout(() => {
      if (studyInstanceUid.value && studyInstanceUid.value.trim() !== '') {
     
        fetchSeriesList();
      }
    }, 100)

  }
})


// 关闭对话框Dialog
const handleClose = () => {
  dialogVisible.value = false

  emit('close')
}


/***
 * 通过StudyId，获取序列列表
*/
const fetchSeriesList = async () => {
  seriesInstanceUidOptions.value = [] //为了方便遍历
  seriesInstanceUid.value = ''

  try {
    // 调用后端API获取序列列表
    const response = await getSeriseAllList({studyId: studyId.value})
    seriesInstanceUidOptions.value = response.data || []

   
  } catch (e) {

    
  }
}


/***
 * 显示Dicom图像
 */

const loadDicomViewer = async () => {


    const series = await getSeriesImages(studyId.value, seriesInstanceUid.value);
    console.log("蓄力数据",series);
    const tempImageIds = series.data.images;

    if(renderingEngine==null){
      console.log("renderingEngine 为Null");
      return;
    }
    const tempViewPort = renderingEngine.getViewport(viewportId);
      //把imageIds 进行协议封装
    const _imageIds=createQiniuImageIds(tempImageIds);
    console.log("imageIDs",_imageIds);
    console.log("=====开始加载====")
    //注册七牛云加载器
    registerQiniuImageLoader();

    console.log("输出引擎",renderingEngine);
    await tempViewPort.setStack(_imageIds);
   

}



/**
 * 注册七牛云图像加载器
 */
function registerQiniuImageLoader() {

  
  imageLoader.registerImageLoader('qiniu', (imageId) => {
    const loadPromise = new Promise(async (resolve, reject) => {
      try {
        const url = imageId.replace('qiniu:', '');
        

        console.log('开始加载七牛云图像:', url);
        const arrayBuffer = await dicomService.fetchDicomDataFromQiniu(url);

  
        // 使用wadouri加载器
        const blob = new Blob([arrayBuffer], { type: 'application/dicom' });
        const blobUrl = URL.createObjectURL(blob);
        const wadUriImageId = `wadouri:${blobUrl}`;
        
        console.log('使用wadouri加载器，临时imageId:', wadUriImageId);
        
        try {
          const dicomImageLoader = cornerstoneDICOMImageLoader.wadouri.loadImage;
      
          const imageLoadObject=dicomImageLoader(wadUriImageId);

          console.log("imageLoadObject",imageLoadObject);
         
          const image = await imageLoadObject.promise;

          console.log('通过wadouri加载器加载成功',image);
        
          
          URL.revokeObjectURL(blobUrl);
          
          return image;

        } catch (wadoError) {
       
          console.error('wadouri加载器失败:', wadoError);
          URL.revokeObjectURL(blobUrl);
          reject(wadoError);
        }

      } catch (error) {
        console.error('七牛云图像加载失败:', error);
        reject(error);
      }
    });

    return {
      promise: loadPromise,
      cancelFn: () => {
        console.log('取消图像加载');
      }
    };
  });
}
/**
 * 初始化组件
 */
const initDicom=async()=>{
    viewportRef.value=document.getElementById("dicom-viewport");


    console.log("====初始化开始====");

    await coreInit();
    await cornerstoneDICOMImageLoader.init();

    const tempRenderingEngine = new RenderingEngine(renderingEngineId);

    const viewportInput = {
      viewportId,
      element:viewportRef.value,
      type: csEnums.ViewportType.STACK,
    };

    
    tempRenderingEngine.enableElement(viewportInput);

    renderingEngine=tempRenderingEngine;
    console.log("====初始化完成====")


}

/**
 * 挂载
 */
onMounted(async () => {
    // 等待Dom 更新完成再 执行
    await nextTick();
})
</script>
<style scoped>
  .viewport {
            width: 800px;
            height: 800px;
          
            margin-top: 20px;
            margin-left: 20px;
          
            background-color: black;
  }
</style>